using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace AppManagement.MainManagers
{
    #region using
    using DevComponents.DotNetBar;
    using AppManagement.Models;
    using AppManagement.Repositories;
    using AppManagement.Helpers;
    using System.Data;
    using System.Drawing;
    using System.IO;
    #endregion

    public partial class FrmQuanLyDiaDiem : Office2007Form
    {
        public FrmQuanLyDiaDiem()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Ham duoc goi khi form duoc load len
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmQuanLyDiaDiem_Load(object sender, EventArgs e)
        {
            InitGridView();
            LoadData();
            dtgvData.ClearSelection();
            btnCapNhat.Enabled = false;
            btnXoa.Enabled = false;
        }

        /// <summary>
        /// Them dia diem moi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnThem_Click(object sender, EventArgs e)
        {
            var errorText = string.Empty;
            if (!ValidateInput(EnumUpdateMode.INSERT, ref errorText))
            {
                MessageBoxEx.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (ActionAdd())
            {
                MessageBoxEx.Show("Lưu dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LoadData();
                btnReset_Click(sender, e);
            }
            else
            {
                MessageBoxEx.Show("Lưu dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Xoa 1 dia diem
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnXoa_Click(object sender, EventArgs e)
        {
            var errorText = string.Empty;
            if (!ValidateInput(EnumUpdateMode.DELETE, ref errorText))
            {
                MessageBoxEx.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (MessageBoxEx.Show("Bạn có chắc chắn xóa dòng này không?", "Xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (ActionDelete())
                {
                    MessageBoxEx.Show("Xóa dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    LoadData();
                    btnReset_Click(sender, e);
                }
                else
                {
                    MessageBoxEx.Show("Xóa dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// Cap nhat dia diem
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCapNhat_Click(object sender, EventArgs e)
        {
            var errorText = string.Empty;
            if (!ValidateInput(EnumUpdateMode.UPDATE, ref errorText))
            {
                MessageBoxEx.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (ActionUpdate())
            {
                MessageBoxEx.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LoadData();
            }
            else
            {
                MessageBoxEx.Show("Cập nhật dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Thoat khoi form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Reset cac fields de them moi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReset_Click(object sender, EventArgs e)
        {
            // Disable btnThem
            btnThem.Enabled = true;
            btnCapNhat.Enabled = false;
            btnXoa.Enabled = false;
            dtgvData.ClearSelection();

            txtMaDiaDiem.Text = string.Empty;
            txtTenDiaDiem.Text = string.Empty;
        }

        /// <summary>
        /// Xu ly su kien click chuot vao grid view
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dtgvData_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dtgvData.SelectedRows == null || dtgvData.SelectedRows.Count == 0)
                return;

            // Disable btnThem
            btnThem.Enabled = false;
            btnCapNhat.Enabled = true;
            btnXoa.Enabled = true;

            var selectedItem = dtgvData.SelectedRows[0];
            txtMaDiaDiem.Text = dtgvData.SelectedRows[0].Cells["MaDiaDiem"].Value.ToString();
            var item = DiaDiemRepository.SelectByID(int.Parse(txtMaDiaDiem.Text));
            LoadDetailInfo(item);
        }

        /// <summary>
        /// Lay thong tin chi tiet dia diem
        /// </summary>
        /// <param name="item"></param>
        public void LoadDetailInfo(DiaDiem item)
        {
            txtTenDiaDiem.Text = item.TenDiaDiem == null ? string.Empty : item.TenDiaDiem.ToString();
            txtDoDai.Text = item.DoDai == null ? string.Empty : item.DoDai.Value.ToString();
        }

        /// <summary>
        /// Khoi tao grid view hien thi du lieu
        /// </summary>
        private void InitGridView()
        {
            DataGridViewTextBoxColumn objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "Mã địa điểm",
                DataPropertyName = "MaDiaDiem",
                Name = "MaDiaDiem",
                Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth) * ((double)1 / 3))
            };
            dtgvData.Columns.Add(objColumn);

            objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "Tên địa điểm",
                DataPropertyName = "TenDiaDiem",
                Name = "TenDiaDiem",
                Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth) * ((double)1 / 3))
            };
            dtgvData.Columns.Add(objColumn);

            objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "Độ dài",
                DataPropertyName = "DoDai",
                Name = "DoDai",
                Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth) * ((double)1 / 3)) - 1
            };
            dtgvData.Columns.Add(objColumn);
        }

        /// <summary>
        /// Load danh sach dia diem
        /// </summary>
        private void LoadData()
        {
            var lstItem = DiaDiemRepository.SelectAll();
            var dt = new DataTable();
            dt.Columns.Add("MaDiaDiem");
            dt.Columns.Add("TenDiaDiem");
            dt.Columns.Add("DoDai");
            for (int i = 0; i < lstItem.Count; i++)
            {
                dt.Rows.Add(lstItem[i].MaDiaDiem, lstItem[i].TenDiaDiem, lstItem[i].DoDai);
            }
            DataView objTimeSheetDV = new System.Data.DataView(dt);
            objTimeSheetDV.AllowNew = false;
            dtgvData.AutoGenerateColumns = false;
            dtgvData.DataSource = lstItem;
            dtgvData.ClearSelection();
        }

        /// <summary>
        /// Validate user input
        /// </summary>
        /// <param name="mode"></param>
        /// <param name="errorText"></param>
        /// <returns></returns>
        private bool ValidateInput(EnumUpdateMode mode, ref string errorText)
        {
            if (mode == EnumUpdateMode.UPDATE || mode == EnumUpdateMode.DELETE)
            {
                if (txtMaDiaDiem.Text == string.Empty)
                {
                    errorText = "Vui lòng chọn mã địa điểm";
                    return false;
                }
            }
            if (mode != EnumUpdateMode.DELETE)
            {
                if (txtTenDiaDiem.Text == string.Empty)
                {
                    errorText = "Vui lòng nhập tên địa điểm";
                    return false;
                }
                double dodai = 0;
                if (double.TryParse(txtDoDai.Text, out dodai))
                {
                    if (dodai <= 0)
                    {
                        errorText = "Độ dài phải lớn hơn 0";
                        return false;
                    }
                }
                else
                {
                    errorText = "Độ dài không phải là số hợp lệ";
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// Ham xy ly them dia diem moi
        /// </summary>
        /// <returns></returns>
        private bool ActionAdd()
        {
            try
            {
                var item = new DiaDiem
                {
                    TenDiaDiem = txtTenDiaDiem.Text,
                    DoDai = double.Parse(txtDoDai.Text)
                };
                if (!DiaDiemRepository.Insert(item))
                {
                    return false;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Ham xu ly cap nhat dia diem
        /// </summary>
        /// <returns></returns>
        private bool ActionUpdate()
        {
            try
            {
                var item = DiaDiemRepository.SelectByID(int.Parse(txtMaDiaDiem.Text));
                item.TenDiaDiem = txtTenDiaDiem.Text;
                item.DoDai = double.Parse(txtDoDai.Text);
                return DiaDiemRepository.Save();
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Ham xu ly xoa dia diem
        /// </summary>
        /// <returns></returns>
        private bool ActionDelete()
        {
            try
            {
                return DiaDiemRepository.Delete(int.Parse(txtMaDiaDiem.Text));
            }
            catch
            {
                return false;
            }
        }

        private void txtDoDai_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar) && (Keys)e.KeyChar != Keys.Back)
            {
                e.Handled = true;
            }
        }
    }
}
